var Login = {
	Unamelink: null,
    Username: null,
	Go: function () {
        var modaldiv = g( 'loginmodal' );
        this.Unamelink = modaldiv.parentNode.getElementsByTagName( 'a' )[ 0 ];
        var loginNode = modaldiv.cloneNode( true );
        var unameInput = loginNode.getElementsByTagName( 'input' )[ 0 ];
        unameInput.value = this.Unamelink.firstChild ? this.Unamelink.firstChild.nodeValue : '';
        loginNode.style.display = '';
        Modals.Create( loginNode, 300, 180 );
        setTimeout( function() {
            unameInput.select();
            unameInput.focus();
        }, 100 );
    },
    Do: function( which ) {
        var username = which.parentNode.getElementsByTagName( 'input' )[ 0 ].value;
        this.Username = username;
        var password = which.parentNode.getElementsByTagName( 'input' )[ 1 ].value;
        Coala.Warm( 'user/login', { 'username': username, 'password': password, 'callback': this.Callback } );
    },
    Callback: function( success ) {
        if ( success ) {
            if ( Login.Unamelink.firstChild ) { 
                Login.Unamelink.firstChild.nodeValue = Login.Username;
            }
            else { // logging in
                Login.Unamelink.appendChild( d.createTextNode( Login.Username ) );
            }
            Login.Unamelink.style.opacity = 0.5;

            setTimeout( function() {
                Animations.Create( Login.Unamelink, 'opacity', 3000, 0.5, 1 );
            }, 2000 );

            Modals.Destroy();

            /* TODO: ajax loading of the whole page
             * the database and table list should be reloaded as the user has changed
             * and also the active database may not be available to the current user
             * so the whole page should be loaded with ajax
             * for now we just refresh the page. */
            window.location.reload();
        }
        else {
            // TODO: Do something better on failure
            alert( 'Access denied' );
        }
	}
};
